﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.SessionState;
using Torch.FrameWork.Common;
using Torch.FrameWork.Configuration;

namespace Torch.WL.Web
{
    public class Global : System.Web.HttpApplication
    {

        protected void Application_Start(object sender, EventArgs e)
        {
        }

        protected void Session_Start(object sender, EventArgs e)
        {

        }

        protected void Application_BeginRequest(object sender, EventArgs e)
        {

        }

        protected void Application_AuthenticateRequest(object sender, EventArgs e)
        {

        }

        protected void Application_Error(object sender, EventArgs e)
        {           
            Exception ex = Server.GetLastError().GetBaseException();
            if (ex != null)
            {
                string errorName = ex.GetType().Name;
                if (errorName == "HttpException")
                {
                    HttpException httpEx = (HttpException)ex;
                    if (httpEx.GetHttpCode() == 404)
                    {
                        return;
                    }
                }

                string msg = "";
                
                string error = msg + "<br>";
                if (ex != null)
                {
                    error += "发生异常页：" + Request.Url.PathAndQuery + "<br>";
                    error += "异常信息：" + ex.Message + "<br>";
                    error += "异常堆栈：" + ex.StackTrace + "<br>";

                    LogEvent.LogError(error.Replace("<br>", "\r\n"));
                }
                
                try
                {
                    //测试环境时显示详细错误
                    if (ConfigurationHelper.Instance().Globals.IsTestRunMode)                  
                        SessionHelper.SetErrorMsg(error);
                    else
                        SessionHelper.SetErrorMsg(string.Empty);
                }
                catch 
                {    
                }

                Response.Redirect("~/Common/ErrorPage.aspx?ReturnUrl=" + System.Web.HttpUtility.UrlEncode(Request.Url.PathAndQuery), false);

            }

            Server.ClearError();


        }

        protected void Session_End(object sender, EventArgs e)
        {
            //Hashtable hOnline = (Hashtable)Application["Online"];
            //if (hOnline[Session.SessionID] != null)
            //{
            //    hOnline.Remove(Session.SessionID);
            //    Application.Lock();
            //    Application["Online"] = hOnline;
            //    Application.UnLock();
            //} 
        }

        protected void Application_End(object sender, EventArgs e)
        {

        }
    }
}